package com.swufe.team;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.collection.ArraySet;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MyTask implements Runnable {
    private static final String TAG = "MyTask";
    private Handler handler;

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void run() {
        //获取网络数据并返回
        Log.i(TAG, "run: Running....");
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        List<String> reList = new ArrayList<String>();
        String curDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
        String logDate = null;
        if (curDateStr.equals(logDate)) {
            //如果相等，则不从网络中获取数据
            Log.i("run", "日期相等，从数据库中获取数据");
            RateManager dbManager = new RateManager(MyTask.this);
            for (RateItem rateItem : dbManager.listAll()) {
                ArraySet<String> retList = new ArraySet<>();
                retList.add(rateItem.getCurName() + "=>" + rateItem.getCurRate());
            }
        } else {
            Log.i("run", "日期相等，从网络中获取在线数据");
            Log.i("run", "curDateStr:" + curDateStr + " logDate:" + logDate);
            try {
                Document doc = Jsoup.connect(" https://www.boc.cn/sourcedb/whpj/  ").get();

                Elements tables = doc.getElementsByTag("table");
                Element table = tables.get(1);
                Elements tds = table.getElementsByTag("td");
                Log.i(TAG, "run: tds" + tds);
                if (tds.size() > 0) {
                    for (int i = 8; i < tds.size(); i += 8) {
                        Element td1 = tds.get(i);
                        Element td2 = tds.get(i + 5);
                        String std1 = td1.text();
                        String std2 = td2.text();
                        reList.add(std1 + std2);
                        Log.i(TAG, "run: " + std1 + "==>" + std2);

                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

            Message msg = handler.obtainMessage(5, reList);
            handler.sendMessage(msg);
            Log.i(TAG, "run: sendMessage ok");
        }
    }
}
